<?php

namespace app\web\home;


use app\web\model\Project as myModel;
use app\web\model\Technician;
use app\web\model\Follow;
use app\web\model\ProjectTechnician;
use app\web\model\Shop;
use app\web\model\User;
use app\lib\model\Tool;

class Project extends Base 
{
    //++++++++++++++++++++++++++用户端
    /**
     * 下单页面获取技师列表
     * [getTechnicianByOrder description]
     * @param  [type] $city       [description]
     * @param  [type] $latitude   [description]
     * @param  [type] $longitude  [description]
     * @param  [type] $project_id [description]
     * @return [type]             [description]
     */
    public function getTechnicianByOrder($city,$latitude,$longitude,$project_id)
    {
        $project = myModel::get($project_id);
        if($project['shop_id'] > 0){  //商家项目
            $map[] = ['id','in',ProjectTechnician::where('project_id',$project_id)->column('technician_id')];
        }else{  //技师项目
            $map[] = ['id','=',$project['technician_id']];
        }
        $map[] = ['city','=',$city];
        $map[] = ['is_online','=',1];
        $map[] = ['check_status','=',1];
        $list = Technician::where($map)->field('id,nickName,avatarUrl,order_number,follow_number,score,longitude,latitude,service_area')->select()->toArray();
        foreach ($list as $key => $value) {
            $list[$key]['distance'] = Tool::getDistance($value['longitude'],$value['latitude'],$longitude,$latitude);
            if(bccomp($list[$key]['distance'], $value['service_area'],2) == 1) unset($list[$key]);
        }
        return show(200,'技师',$list);
    }
    /**
     * 技师详情页推荐项目
     * [getList description]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function getList($id){
        $technician = Technician::get($id);
        if($technician['shop_id'] > 0){   //已绑定商户
            $where[] = ['a.all_status','=',1];
            $where[] = ['a.status','=',1];
            $ids = ProjectTechnician::getProjectIdByTechnician($id,$technician['shop_id']);
            $idss = myModel::where(['technician_id'=>$id,'all_status'=>1,'status'=>1])->column('id');
            $where[] = ['a.id','in',array_merge($ids,$idss)];
        }else{    //未绑定商家
            $where = ['a.technician_id'=>$id,'a.all_status'=>1,'a.status'=>1];
        }
        return show(200,'项目列表',$this->get($where));
    }
    
    /**
     * 列表页项目列表
     * [getAll description]
     * @return [type] [description]
     */
    public function getAll(){
        $params = input('post.');
        $where[] = ['a.all_status','=',1];
        $where[] = ['a.status','=',1];
        if(!empty($params['category_id'])){
            $where[] = ['a.category_id','=',(int)$params['category_id']];
        }
        if(!empty($params['shop_id'])){
            $where[] = ['a.shop_id','=',(int)$params['shop_id']];
        }
        $order = 'a.money';
        if(isset($params['order'])){

            switch($params['order']){
                case '0':
                    $order = 'a.order_number desc,a.score desc,a.money,a.create_time desc';
                    break;
                case '1':
                    $order = 'a.order_number desc';
                    break;
                case '3':
                    $order = 'a.create_time desc';
                    break;
                case '4':
                    $order = 'a.score desc,a.order_number desc';
                    break;
                case '5':
                    $order = 'a.money,a.order_number desc';
                    break;
                case '6':
                    $order = 'a.money desc,a.order_number desc';
                    break;
                default:
                    $order = 'a.order_number';  
            }
        }
        return show(200,'项目列表',$this->get($where,$order));
    }
    /**
     * 用户端项目详情
     * [find description]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function find($id)
    {
        $list = myModel::alias('a')
                        ->where('a.id',$id)
                        ->field('a.id,a.technician_id,a.shop_id,a.project_name,a.position_name,a.order_number,a.image,a.project_images,a.money,a.project_desc,a.service_time')
                        ->find()->toArray();

        $list['image'] = $list['image'] ? explode(',', $list['image']) : [];
        $list['project_images'] = $list['project_images'] ? explode(',', $list['project_images']) : [];
        $list['is_follow'] = Follow::isFollow($id,$this->uid,false);
        if($list['shop_id'] > 0){
            $where = ['id'=>ProjectTechnician::where(['project_id'=>$list['id']])->column('technician_id')];
        }else{
            $where = ['id'=>$list['technician_id']];
        }
        $where['check_status'] = 1;
        $where['is_online'] = 1;

        $technician_list = Technician::where($where)->field('id,nickName,avatarUrl,order_number,follow_number,score,longitude,latitude')->select()->toArray();
        $user = User::get($this->uid);
        foreach ($technician_list as $key => $value) {
            $technician_list[$key]['distance'] = Tool::getDistance($user['longitude'],$user['latitude'],$value['longitude'],$value['latitude']);
        }
        $list['technician_list'] = $technician_list;
        return show(200,'项目详情',$list);
    }
    private function get($where,$order = 'a.money')
    {
        return myModel::alias('a')->where($where)
            ->where('d.is_sale=1 and d.is_sale1=1 and d.is_online=1 and d.is_period=0 and d.is_project=1')
            ->leftJoin('project_technician c','c.project_id=a.id')
            ->leftJoin('technician d','d.id=c.technician_id')
            ->leftjoin('shop b','b.id=a.shop_id')
            ->field('a.id,a.project_name,a.service_time,a.order_number,a.money,a.image,ifnull(b.shop_name,"") as shop_name')
            ->order($order)
            ->group('a.id')
            ->paginate()->each(function($v,$k){
                $v['image'] = explode(',', $v['image'])[0];
            });
    }
    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //
    /**
     * 创建项目
     * [create description]
     * @return [type] [description]
     */
    public function create()
    {
        if($this->auth_status == 2) return show(400,'无操作权限');
        $post = input('post.');
        if($this->appkey == 1){  //技师端
            $post['technician_id'] = $this->getCurrentId();
            if($post['technician_id'] == 0) return show(400,'未通过审核,不可创建项目');
            $shop_id = Technician::where(['id'=>$post['technician_id']])->value('shop_id');
            if($shop_id == 0){
                $post['shop_check_status'] = 1;
            }
            $post['is_dis'] = 1;
        }else{  //商家端
            $post['shop_id'] = $this->getCurrentId();
            $post['shop_check_status'] = 1;
            if($post['shop_id'] == 0) return show(400,'未通过审核,不可创建项目');
        }
        $this->validate($post,'Project');
        $res = myModel::create($post);
        if($res->isEmpty()) return show(400,'提交失败');
        if($this->appkey == 1){  
            ProjectTechnician::create([
                'project_id' => $res->id,
                'technician_id' => $post['technician_id'],
            ]);
        }
        return show(200,'提交成功');
    }
    /**
     * 修改项目
     * [edit description]
     * @return [type] [description]
     */
    public function edit()
    {
        if($this->auth_status == 2) return show(400,'无操作权限');
        $post = input('post.');
        $this->validate($post,'Project');
        $info = myModel::get($post['id']);
        $post['all_status'] = 0;
        $post['status'] = 0;
        $post['check_status'] = 0;
        $post['check_time'] = null;
        $post['check_uid'] = 0;
        $post['check_desc'] = '';
        $post['shop_check_status'] = 0;
        $post['shop_check_time'] = null;
        $post['shop_check_uid'] = 0;
        $post['shop_check_desc'] = '';
        $res = $info->save($post);
        if($res) {
            myModel::setIsProject($post['id']);
            return show(200,'修改成功');
        }
        return show(400,'修改失败');
    }
    /**
     * 技师推荐/未推荐
     * [recommend description]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function recommend($id)
    {
        if($this->auth_status == 2) return show(400,'无操作权限');
        $info = myModel::get($id);
        if($this->appkey == 1){  //技师端推荐
            $shop = Technician::get($this->getCurrentId());
            $project_recommend = myModel::where(['technician_id'=>$shop->id,'is_recommend'=>1])->count();
        }else{
            $shop = Shop::where(['user_id'=>$this->uid])->find();
            $project_recommend = myModel::where(['shop_id'=>$shop->id,'is_recommend'=>1])->count();
        }
        
        if($info->is_recommend == 0 && $project_recommend >= $shop['project_recommend']){
            return show(400,'最多可推荐'.$shop['project_recommend'].'个项目');
        }
        $info->is_recommend = $info->is_recommend == 1 ? 0 : 1;
        if($info->save()){
            return show(200,'操作成功');
        }
        return show(400,'操作失败');
    }
    
    /**
     * 商户端审核
     * [checkProject description]
     * @return [type] [description]
     */
    public function checkProject()
    {
        if($this->auth_status == 2) return show(400,'无操作权限');
        $post = input('post.');
        if($post['shop_check_status'] == 2 && empty($post['shop_check_desc'])){
            return show(400,'请输入不予通过原因');
        }
        $info = myModel::get($post['id']);
        $info['shop_check_status'] = $post['shop_check_status'];
        $info['shop_check_time'] = time();
        $info['shop_check_desc'] = $post['shop_check_desc'] ?? '';

        if($info['shop_check_status'] == 2){
            $info['all_status'] = 2;
        }
        if($info['shop_check_status'] == 1 && $info['check_status'] == 1){
            $info['all_status'] = 1;
        }
        if($info->save()) {
            myModel::setIsProject($info->id);
            return show(200,'审核成功'); 
        }
        return show(400,'审核失败');
    }
    /**
     * 商户端分配技师
     * [distribution description]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function distribution($id = 0,$status = 0)
    {
        if($this->auth_status == 2) return show(400,'无操作权限');
        $shop_id = $this->getCurrentId();
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $ids = ProjectTechnician::where(['project_id'=>$data['id']])->update(['delete_time'=>time()]);
            if(empty($data['ids'])){
                myModel::where('id',$data['id'])->update(['is_dis'=>0]);
                myModel::setIsProject($data['id']);
                return show(200,'分配成功');
            } 
            $ids = is_array($data['ids']) ? $data['ids'] : explode(',',$data['ids']);
            $arr = [];
            foreach ($ids as $key => $value) {
                $arr[] = [
                    'project_id' => $data['id'],
                    'technician_id' => $value,
                    'shop_id' => $shop_id
                ];
            }
            $res = (new ProjectTechnician())->saveAll($arr);
            if($res){
                myModel::setIsProject($data['id']);
                myModel::where('id',$data['id'])->update(['is_dis'=>1]);
                return show(200,'分配成功'); 
            }
            return show(400,'分配失败');
        }
        if($shop_id == 0) return show(400,'无权限分配技师');

        $ids = ProjectTechnician::where(['project_id'=>$id])->column('technician_id');
        if($status == 1){
            $ids = ProjectTechnician::where(['project_id'=>$id])->column('technician_id');
            $technician = Technician::where(['shop_id'=>$shop_id,'check_status'=>1])->where('id','in',$ids)->field('id,nickName,avatarUrl')->select();
        }else{
            $technician = Technician::where(['shop_id'=>$shop_id,'check_status'=>1])->field('id,nickName,avatarUrl')->select();
        }
        
        foreach ($technician as $key => $value) {
            if(in_array($value['id'], $ids)){
                $technician[$key]['selected'] = 1;
            }else{
                $technician[$key]['selected'] = 0;
            }
        }
        return show(200,'技师列表',$technician);
    }
    /**
     * 上架下架
     * [shelves description]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function shelves($id)
    {
        if($this->auth_status == 2) return show(400,'无操作权限');
        $info = myModel::get($id);
//        if($this->appkey == 1 && $info->status != 1){
//            $t = Technician::get($info->technician_id);
//            if($t->is_sale1 != 1 || $t->is_sale != 1){
//                $arr = Technician::getCheckMessage($info->technician_id);
//                if($arr) return show(400,$arr[0]);
//                return show(400,'您已被下架');
//            }
//            if($t->is_period == 1){
//                return show(400,'已到合作期限,请联系平台');
//            }
//        }
        $info->status = $info['status'] == 1 ? 0 : 1;
        if($info->save()){
            myModel::setIsProject($id);
            return show(200,'操作成功');
        }
        return show(400,'操作失败');
    }
    /**
     * 项目详情
     * [info description]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function info($id)
    {
        $info = myModel::alias('a')
                        ->leftjoin('category b','b.id=a.category_id')
                        ->leftjoin('technician c','c.id=a.technician_id')
                        ->where('a.id',$id)
                        ->field('a.id,a.image,a.category_id,a.project_name,a.position_name,a.service_time,a.money,a.project_desc,a.project_images,a.all_status,b.category_name,a.check_status,a.create_time,a.shop_check_status,a.shop_check_desc,a.check_desc,c.avatarUrl,c.nickName')
                        ->find()->toArray();
        if($this->appkey == 1){  //技师端
            $technician = Technician::where('id',$this->getCurrentId())->find();
            $info['is_shop'] = $technician['shop_id'] == 0 ? 0 : 1; //是否绑定商家
            $info['avatarUrl'] = $info['avatarUrl'] ? $info['avatarUrl'] : $technician['avatarUrl'];
            $info['nickName'] = $info['nickName'] ? $info['nickName'] :$technician['nickName'];
        }elseif($this->appkey == 2){  //商家端
            $info['my_technician'] = Technician::where(['shop_id'=>$this->getCurrentId(),'check_status'=>1])->field('id,nickName,avatarUrl')->select();

        }
        $info['image'] = $info['image'] ? explode(',',$info['image']) : [];
        $info['project_images'] = $info['project_images'] ? explode(',',$info['project_images']) : [];
        return show(200,'项目详情',$info);
    }
    /**
     * 删除项目
     * [del description]
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function del($id){
        if($this->auth_status == 2) return show(400,'无操作权限');
        if(myModel::destroy($id)){
            myModel::setIsProject($id);
            return show(200,'删除成功');
        }
        return show(400,'删除失败');
    }
    /**
     * 项目列表
     * [list description]
     * @param  integer $status [description]
     * @return [type]          [description]
     */
    public function list($status = 0)
    {
        $map = [];
        if($this->appkey == 1){
            $technician_id = $this->getCurrentId();
            $shop_id = Technician::where(['user_id'=>$this->uid])->value('shop_id');
            if($status == 0){
                $map[] = ['a.technician_id','=',$technician_id];
                $map[] = ['a.all_status','=',1];
            }
            if($status == 1){  //技师端商家分配项目
                if($shop_id == 0){
                    return show(200,'项目列表',[]);
                }else{
                    $project_ids = ProjectTechnician::getProjectIdByTechnician($technician_id,$shop_id);
                    if(!$project_ids) return show(200,'项目列表',[]);
                    $map[] = ['a.id','in',$project_ids];
                    $map[] = ['a.shop_check_status','=',1];
                    $map[] = ['a.check_status','=',1];
                }
            }
            if($status == 2){   //技师端待审核项目
                $map[] = ['a.technician_id','=',$technician_id];
                $map[] = ['a.all_status','<>',1];
            }
        }else{
            $shop_id = $this->getCurrentId();
            if($status == 0){
                $map[] = ['a.shop_id','=',$shop_id];
                $map[] = ['a.all_status','=',1];
            }else if($status == 1){
                $map[] = ['a.shop_id','=',$shop_id];
                $map[] = ['a.all_status','<>',1];
            }else if($status == 2){   //技师项目
                $technician_ids = Technician::where(['shop_id'=>$shop_id])->column('id');
                if(!$technician_ids) return show(200,'项目列表',[]);
                $map[] = ['a.technician_id','in',$technician_ids];
                $map[] = ['a.all_status','=',1];
            }else if($status == 3){
                $technician_ids = Technician::where(['shop_id'=>$shop_id])->column('id');
                if(!$technician_ids) return show(200,'项目列表',[]);
                $map[] = ['a.technician_id','in',$technician_ids];
                $map[] = ['a.all_status','<>',1];
            }
        }
        $list = myModel::alias('a')
                        ->where($map)
                        ->leftjoin('category b','b.id=a.category_id')
                        ->leftjoin('technician c','c.id=a.technician_id')
                        ->field('a.id,b.category_name,a.project_name,a.image,a.service_time,a.money,a.order_number
                            ,a.status,a.all_status,a.is_recommend,a.is_dis,c.nickName,c.avatarUrl')
                        ->order('a.create_time desc')
                        ->paginate()->each(function($item,$k){
                            $item['image'] = $item['image'] ? explode(',', $item['image'])[0] : '';
                            return $item;
                        });
        return show(200,'项目列表',$list);
    }
}